package com.sztu.shirocore;


import com.alibaba.fastjson.JSON;
import com.mysql.cj.util.StringUtils;
import com.sztu.token.JwtToken;
import com.sztu.token.LoginType;
import com.sztu.utils.JwtUtil;
import com.sztu.utils.Result;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class JwtFilter extends AuthenticatingFilter {

    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        String jwt=request.getHeader("Authorization");
        if(StringUtils.isNullOrEmpty(jwt)){
            return null;
        }
        return new JwtToken(jwt).setLoginType(LoginType.SHIRO_USER);
    }

    // 验证token
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        String jwt=request.getHeader("Authorization");
        if(JwtUtil.verifyToken(jwt)!=0){
               HttpServletResponse response= (HttpServletResponse) servletResponse;
               response.setContentType("application/plain;charset=utf-8");
               PrintWriter writer=response.getWriter();
               writer.write(JSON.toJSONString(new Result().setCode(401).setMessage("token失效,请重新登录")));
               return false;
        }

        return executeLogin(servletRequest,servletResponse);

    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        HttpServletResponse httpServletResponse= (HttpServletResponse) response;
        Throwable throwable=e.getCause()==null?e:e.getCause();
        try {
            httpServletResponse.getWriter().print(new Result().setMessage(e.getMessage()));
        }catch (IOException ioException){

        }
        return false;
    }
}
